<template>
  <div class="login-container">
    <div class="login-box">
      <!-- Logo 和标题 -->
      <div class="logo-section">
        <img src="@/assets/logo.png" alt="盒游纪"/>
        <div class="title">
          <h2>欢迎来到盒游纪</h2>
          <p>总有一款你热爱的游戏</p>
        </div>
      </div>

      <!-- 登录表单 -->
      <van-form @submit="handleLogin">
        <van-cell-group inset>
          <van-field
              v-model="loginForm.email"
              name="email"
              placeholder="邮箱"
              :rules="[{ required: true, message: '请输入邮箱' }, { pattern: /^[\w.-]+@[\w.-]+\.\w+$/, message: '请输入正确的邮箱格式' }]"
          >
            <template #left-icon>
              <van-icon name="envelop-o" />
            </template>
          </van-field>

          <van-field
              v-model="loginForm.password"
              type="password"
              name="password"
              placeholder="密码"
              :rules="[{ required: true, message: '请输入密码' }, { min: 6, message: '密码长度不能少于6位' }]"
          >
            <template #left-icon>
              <van-icon name="lock" />
            </template>
          </van-field>
        </van-cell-group>

        <!-- 同意服务条款 -->
        <div class="terms">
          <van-checkbox v-model="loginForm.agreeTerms" checked-color="#00bfff">
            登录表示您已同意
            <span class="terms-link" @click="showTerms">《盒游纪服务条款》</span>
          </van-checkbox>
        </div>

        <div style="margin: 16px;">
          <van-button
              round
              block
              type="primary"
              native-type="submit"
              :loading="loading"
              :disabled="!loginForm.agreeTerms"
          >
            立即登录
          </van-button>
        </div>
      </van-form>

      <div class="register-link">
        还没有账号？<span class="register-link-text" @click="goToRegister">立即注册</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue';
import axios from '@/utils/axios';
import {useRouter, useRoute} from 'vue-router';
import { showFailToast, showSuccessToast } from 'vant';
import 'vant/es/toast/style';

// 路由实例，用于页面跳转
const router = useRouter();
const route = useRoute();

// 表单数据接口定义
interface LoginFormData {
  email: string;
  password: string;
  agreeTerms: boolean; // 新增字段：是否同意服务条款
}

// 登录表单响应式数据
const loginForm = reactive<LoginFormData>({
  email: '',
  password: '',
  agreeTerms: false // 默认未勾选
});

// 控制登录按钮加载状态的响应式变量
const loading = ref(false);

// 页面加载时尝试恢复表单数据
onMounted(() => {
  // 检查是否有注册成功地查询参数
  const urlParams = new URLSearchParams(window.location.search);
  if (urlParams.get('registerSuccess') === 'true') {
    showSuccessToast('注册成功，请登录');
  }

  // 尝试恢复表单数据
  const savedFormData = sessionStorage.getItem('loginFormData');
  if (savedFormData) {
    try {
      const parsedData = JSON.parse(savedFormData);
      loginForm.email = parsedData.email || '';
      loginForm.password = parsedData.password || '';
      loginForm.agreeTerms = parsedData.agreeTerms || false;
      // 恢复后清除存储的数据
      sessionStorage.removeItem('loginFormData');
    } catch (e) {
      console.error('Failed to parse saved form data', e);
    }
  }
});

// 监听表单数据变化并保存到 sessionStorage
const saveFormData = () => {
  sessionStorage.setItem('loginFormData', JSON.stringify({...loginForm}));
};

/**
 * 显示服务条款信息
 * 该函数用于在用户点击服务条款时跳转到服务条款页面
 */
const showTerms = () => {
  // 保存当前表单数据
  saveFormData();
  router.push('/terms?from=login');
};

/**
 * 跳转到注册页面
 */
const goToRegister = () => {
  router.push('/register');
};

/**
 * 处理用户登录逻辑
 * 包含表单校验、发送登录请求、存储token和页面跳转等操作
 */
const handleLogin = async () => {
  if (!loginForm.agreeTerms) {
    showFailToast('请先同意服务条款');
    return;
  }

  try {
    loading.value = true;

    // 移除 agreeTerms 字段，因为后端不需要这个字段
    const { agreeTerms, ...loginData } = loginForm;

    const response = await axios.post('/api/users/login', loginData);
    console.log(response)
    // 兼容多种响应结构，提取 token 与 userId
    const raw = (response as any)?.data ?? response
    const token = raw?.token || raw?.data?.token || raw?.result?.token
    const userId = raw?.userId || raw?.data?.userId || raw?.user?.userId || raw?.user?.id
    if (token) {
      // 存储 token（兼容本项目 axios 从 localStorage 读取）
      localStorage.setItem('token', token)
      sessionStorage.setItem('token', token)
    }
    if (userId != null) {
      localStorage.setItem('userId', String(userId))
    }
    showSuccessToast('登录成功');
    // 登录后跳回来源页（redirect），否则去首页
    const redirect = (route.query.redirect as string) || ''
    await router.push(redirect ? decodeURIComponent(redirect) : '/home');
  } catch (error: any) {
    if (error.response && error.response.status === 404) {
      showFailToast('登录接口未找到，请检查网络连接或联系管理员');
    } else {
      showFailToast('登录失败，请检查网络连接');
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.login-box {
  width: 100%;
  max-width: 350px;
  padding: 30px 20px;
  border-radius: 8px;
  background: white;
  z-index: 100;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.logo-section {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  flex-direction: column;
}

.logo-section img {
  width: 80px;
  height: 80px;
  margin-right: 0;
  margin-bottom: 15px;
}

.logo-section .title {
  text-align: center;
}

.logo-section .title h2 {
  color: #00bfff;
  font-size: 24px;
  margin: 0;
}

.logo-section .title p {
  color: #999;
  font-size: 14px;
  margin: 5px 0 0;
}

.terms {
  font-size: 12px;
  color: #666;
  text-align: center;
  margin: 15px 0;
}

.terms-link {
  color: #00bfff;
  cursor: pointer;
}

.register-link {
  text-align: center;
  font-size: 14px;
  color: #666;
  margin-top: 20px;
}

.register-link-text {
  color: #00bfff;
  cursor: pointer;
}

:deep(.van-button--disabled) {
  opacity: 0.6;
}
</style>
